package com.tom.commonframework.common.net.downloads.server;

import android.app.IntentService;
import android.content.Intent;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.lkn.net.interceptor.DownloadProgressInterceptor;
import com.tom.commonframework.common.net.downloads.entity.DownloadEntity;
import com.tom.commonframework.common.net.downloads.utils.DownloadUtils;

import java.io.File;
import java.util.ArrayList;

import rx.Subscriber;

/**
 * Created by TomLeisen on 2018/7/16
 * Email: xy162162a@163.com
 * Description:
 */
public class DownloadService extends IntentService {
    private static final String TAG = DownloadService.class.getName();

    int downloadCount = 0;
    private static final String DIR = Environment.getExternalStorageDirectory() + "/DownloadCacheTest/tmp/";
    public static ProgressListeners progressListeners;
    private DownloadEntity download;
    private String download_url;
    private String file_name;
    private String file_address;//文件存储地址
    public static final String FILE_ADDRESS = "file_address";
    public static final String DOWNLOAD_URL = "download_url_str";
    public static final String FILE_NAME = "file_name_str";
    public static final String DOWNLOAD_URL_LIST = "download_url_list";
    public static final String FILE_NAME_LIST = "file_name_list";


    public DownloadService() {
        super("DownloadService");
    }

    private File outputFile;

    @Override
    protected void onHandleIntent(Intent intent) {
        file_address = intent.getStringExtra(FILE_ADDRESS);
        download_url = intent.getStringExtra(DOWNLOAD_URL);
        file_name = intent.getStringExtra(FILE_NAME);
        ArrayList<String> urlList = intent.getStringArrayListExtra(DOWNLOAD_URL_LIST);
        ArrayList<String> fileNameList = intent.getStringArrayListExtra(FILE_NAME_LIST);
        if (urlList != null && urlList.size() != 0) {
            for (int i = 0; i < urlList.size(); i++) {//循环启动任务
                download_url = urlList.get(i);
                file_name = fileNameList.get(i);
                download(file_name);
            }
        } else {
            download(file_name);
        }
    }

    @Override
    public void onStart(@Nullable Intent intent, int startId) {
        super.onStart(intent, startId);
    }

    private void download(final String file_name) {
        DownloadProgressInterceptor.DownloadProgressListener listener = new DownloadProgressInterceptor.DownloadProgressListener() {
            @Override
            public void update(long bytesRead, long contentLength, int progress, boolean done) {
                if ((downloadCount == 0) || progress > downloadCount) {
                    download = new DownloadEntity();
                    download.setCurrentFileSize(bytesRead);
                    download.setTotalFileSize(contentLength);
                    download.setProgress(progress);
                    download.setCurrentFileSizeStr(DownloadUtils.getDataSize(download.getCurrentFileSize()));
                    download.setTotalFileSizeStr(DownloadUtils.getDataSize(download.getTotalFileSize()));
                    progressListeners.progressListeners(progress, download.getCurrentFileSizeStr(), download.getTotalFileSizeStr());
                }
            }
        };

        outputFile = new File(!TextUtils.isEmpty(file_address) ? file_address : DIR, file_name);
        if (outputFile.exists()) {
            outputFile.delete();
        }

        new DownloadAPI(download_url, listener, outputFile, new Subscriber() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                progressListeners.onError(e.getMessage(), e);
            }

            @Override
            public void onNext(Object object) {
                progressListeners.onNext(object, !TextUtils.isEmpty(file_address) ? file_address + file_name : DIR + file_name);
            }
        });
    }


    @Override
    public void onTaskRemoved(Intent rootIntent) {

    }


    public interface ProgressListeners {
        /**
         * @param progress        进度  Max = 100
         * @param currentFileSize 当前的文件大小
         * @param totalFileSize   总文件大小
         */
        void progressListeners(int progress, String currentFileSize, String totalFileSize);

        /**
         * 下载成功
         *
         * @param filePath 下载的文件路径
         */
        void onNext(Object object, String filePath);

        /**
         * 下载失败
         */
        void onError(String errorMsg, Throwable e);


    }

    public static void setProgressListeners(ProgressListeners progress) {
        progressListeners = progress;
    }
}
